package com.example.jn_dxs.Utlis;

import com.esri.arcgisruntime.arcgisservices.LevelOfDetail;
import com.esri.arcgisruntime.arcgisservices.TileInfo;
import com.esri.arcgisruntime.data.TileKey;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ImageTiledLayer;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author zzx
 * @Date 2019/2/22-8:46
 * @Desc 天地图
 */
public class TMapLayer extends ImageTiledLayer {

    // 枚举
    public enum MapType {
        T_VECTOR_2000,    // 天地图矢量图
        T_VECTOR_ANNOTATION_CHINESE_2000,    // 天地图矢量图注记
        T_IMAGE_2000,    // 天地图影像图
        T_IMAGE_ANNOTATION_CHINESE_2000,    // 天地图影像图注记
    }

    private static TileInfo mTileInfo;
    private MapType mMapType;

    private TMapLayer(TMapLayer.MapType mapType, TileInfo tileInfo, Envelope fullExtent) {
        super(tileInfo, fullExtent);
        this.mMapType = mapType;
    }

    public static TMapLayer getTMap(TMapLayer.MapType mapType) {
        TileInfo tileInfo = buildTileInfo();
        return new TMapLayer(mapType, tileInfo, ENVELOPE_2000);
    }

//    @Override
//    protected byte[] getTile(TileKey tileKey) {
//
////        LogUtil.d(getMapUrl(tileKey));
//        byte[] iResult = null;
//        try {
//            URL iURL = null;
//            byte[] iBuffer = new byte[1024];
//            HttpURLConnection iHttpURLConnection = null;
//            BufferedInputStream iBufferedInputStream = null;
//            ByteArrayOutputStream iByteArrayOutputStream = null;
//
//            iURL = new URL(getMapUrl(tileKey));
//            iHttpURLConnection = (HttpURLConnection) iURL.openConnection();
//            iHttpURLConnection.connect();
//            iBufferedInputStream = new BufferedInputStream(iHttpURLConnection.getInputStream());
//            iByteArrayOutputStream = new ByteArrayOutputStream();
//            while (true) {
//                int iLength = iBufferedInputStream.read(iBuffer);
//                if (iLength > 0) {
//                    iByteArrayOutputStream.write(iBuffer, 0, iLength);
//                } else {
//                    break;
//                }
//            }
//            iBufferedInputStream.close();
//            iHttpURLConnection.disconnect();
//
//            iResult = iByteArrayOutputStream.toByteArray();
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return iResult;
//    }
    @Override
    protected byte[] getTile(TileKey tileKey) {
        try {
            URL url = new URL(getMapUrl(tileKey));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            //获取服务器返回回来的流
            InputStream is = conn.getInputStream();
            return getBytes(is);
        } catch (Exception e) {
            return new byte[0];
        }
    }
    private byte[] getBytes(InputStream is) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        is.close();
        bos.flush();
        byte[] result = bos.toByteArray();
        System.out.println(new String(result));
        return result;
    }

    private String getMapUrl(TileKey tileKey) {
        String iResult;
        Random iRandom;
        int level = tileKey.getLevel();
        int col = tileKey.getColumn();
        int row = tileKey.getRow();
        String mapUrl;
        String layerName;
        iResult = "http://t";
        iRandom = new Random();
        iResult = iResult + iRandom.nextInt(4);
        baseUrl = iResult+".tianditu.gov.cn/";

        switch (this.mMapType) {
            case T_VECTOR_2000:
                mapUrl = URL_VECTOR_2000;
                layerName = LAYER_NAME_VECTOR;
                break;
            case T_VECTOR_ANNOTATION_CHINESE_2000:
                mapUrl = URL_VECTOR_ANNOTATION_CHINESE_2000;
                layerName = LAYER_NAME_VECTOR_ANNOTATION_CHINESE;
                break;
            case T_IMAGE_2000:
                mapUrl = URL_IMAGE_2000;
                layerName = LAYER_NAME_IMAGE;
                break;
            case T_IMAGE_ANNOTATION_CHINESE_2000:
                mapUrl = URL_IMAGE_ANNOTATION_CHINESE_2000;
                layerName = LAYER_NAME_IMAGE_ANNOTATION_CHINESE;
                break;
            default:
                return null;
        }

        return mapUrl + "?service=wmts&request=gettile&version=1.0.0&layer="
                + layerName + "&format=tiles&STYLE=default&tilematrixset="
                + TILE_MATRIX_SET_2000 + "&tilecol=" + col
                + "&tilerow=" + row + "&tilematrix=" + (level + 1) + "&tk=" + tidituKey;
    }

    @Override
    public TileInfo getTileInfo() {
//        LogUtil.i("getTileInfo");
        return mTileInfo;
    }

    private static TileInfo buildTileInfo() {
        List<LevelOfDetail> levelOfDetails = new ArrayList<>();
        for (int i = 0; i < RESOLUTIONS_2000.length; i++) {
            LevelOfDetail levelOfDetail = new LevelOfDetail(i, RESOLUTIONS_2000[i], SCALES[i]);
            levelOfDetails.add(levelOfDetail);
        }
        mTileInfo = new TileInfo(DPI, TileInfo.ImageFormat.PNG, levelOfDetails, ORIGIN_2000, SRID_2000, tileHeight, tileWidth);
        return mTileInfo;
    }

    /* 天地图配置 */
    private static final int DPI = 96;
    private static final int tileWidth = 256;
    private static final int tileHeight = 256;
    private static final String LAYER_NAME_VECTOR = "vec";
    private static final String LAYER_NAME_VECTOR_ANNOTATION_CHINESE = "cva";
    private static final String LAYER_NAME_IMAGE = "img";
    private static final String LAYER_NAME_IMAGE_ANNOTATION_CHINESE = "cia";

    private static final SpatialReference SRID_2000 = SpatialReference.create(4490);
    private static final double X_MIN_2000 = -180;
    private static final double Y_MIN_2000 = -90;
    private static final double X_MAX_2000 = 180;
    private static final double Y_MAX_2000 = 90;

    private static final Point ORIGIN_2000 = new Point(-180, 90, SRID_2000);
    private static final Envelope ENVELOPE_2000 = new Envelope(X_MIN_2000, Y_MIN_2000, X_MAX_2000, Y_MAX_2000, SRID_2000);


    private static String baseUrl = "http://t0.tianditu.gov.cn";
    // 矢量底图
    private static final String URL_VECTOR_2000 = baseUrl + "/vec_c/wmts";
    // 矢量地名
    private static final String URL_VECTOR_ANNOTATION_CHINESE_2000 = baseUrl + "/cva_c/wmts";
    // 影像图底图
    private static final String URL_IMAGE_2000 = baseUrl + "/img_c/wmts";
    // 影像图地名
    private static final String URL_IMAGE_ANNOTATION_CHINESE_2000 = baseUrl + "/cia_c/wmts";

    private static final String TILE_MATRIX_SET_2000 = "c";

    private static final double[] SCALES = {
            2.958293554545656E8, 1.479146777272828E8,
            7.39573388636414E7, 3.69786694318207E7,
            1.848933471591035E7, 9244667.357955175,
            4622333.678977588, 2311166.839488794,
            1155583.419744397, 577791.7098721985,
            288895.85493609926, 144447.92746804963,
            72223.96373402482, 36111.98186701241,
            18055.990933506204, 9027.995466753102,
            4513.997733376551, 2256.998866688275,
            1128.4994333441375
    };

    private static final double[] RESOLUTIONS_2000 = {
            0.7031249999891485, 0.35156249999999994,
            0.17578124999999997, 0.08789062500000014,
            0.04394531250000007, 0.021972656250000007,
            0.01098632812500002, 0.00549316406250001,
            0.0027465820312500017, 0.0013732910156250009,
            0.000686645507812499, 0.0003433227539062495,
            0.00017166137695312503, 0.00008583068847656251,
            0.000042915344238281406, 0.000021457672119140645,
            0.000010728836059570307, 0.000005364418029785169};

    private static String tidituKey = "d23c1b71311e49421e15419756cd9df6";
}